<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>APP</title>
    <meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1,user-scalable=0" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <link rel="stylesheet" href="css/mui.min.css" />
    <link rel="stylesheet" href="css/mui.picker.min.css" />
    <link rel="stylesheet" href="css/main.css" />
  </head>
  <body>
    <div id="app">
      <div id="loader" :class="{loaded : loaded}">
          <span class="mui-spinner"></span>
          <div>加载中, 请稍候...</div>    
      </div>
      <ul id="fillInfo" :class="{fadeOut: started}">
        <li>
          <h3>答题系统</h3>
        </li>
        <li>
            <div class="myUnit">
            <button @click="selectUnit">{{myUnit === '' ? '请选择单位' : myUnit}}</button>
          </div>
        </li>
        <li>
          <div class="myName">
            <button v-show="!inputName" @click="selectName">{{myName === '' ? '请选择名字' : myName}}</button>
            <input type="text" v-model.trim="myName" placeholder="请输入您的名字"  v-show="inputName" />
          </div>
        </li>
        <li>
          <button id="startBtn" class="subBtn" @click="start">开始答题</button>
        </li>
      </ul>
      <div class="scrollBtn">
        <button @click="scroll(0)"><span class="mui-icon mui-icon-arrowup"></span></button>
        <button @click="scroll(1)"><span class="mui-icon mui-icon-arrowdown"></span></button>
      </div>
      <div id="topic" :class="{show : started}">
        <h1>
          总共{{topic.length}}题，总分100分。<small>考试剩余时间<b>{{countTime}}</b></small>
        </h1>
        <ul>
          <li v-for="(x, xindex) in topic" :class="checked && x.select.type === '' ? 'undo' : ''">
            <h4>{{xindex+1}}.{{x.question}}<i>*</i></h4>
            <div class="mui-card">
              <ul class="mui-card-content-inner">
                <li v-for="(y, yindex) in x.answer" class="mui-input-row mui-radio mui-left">
                  <label>
                    <input :name="'radio'+xindex" type="radio" @click="fillAnswer" :data-val="xindex+'|'+yindex">{{y.type}}.{{y.text}}
                  </label>
                </li>
              </ul>
            </div>
          </li>
        </ul>
        <div class="txc">
          <button @click="finish" id="endBtn" class="subBtn">立即交卷</button>
        </div>
      </div>
      <div id="result" :class="{show : finished}">
        <div class="userInfo">
          <div>个人信息</div>
          <p>姓名：{{myName}}</p>
          <p>单位：{{myUnit}}</p>
        </div>
        <div class="ranking">
          <div class="left">
            <span>得分</span>
            <div>{{score}}</div>
          </div>
          <div class="right">
            <ul>
              <li>总共用时：<span>{{useTime}}</span></li>
              <li>您的名次：<span><b>{{result.ranking}}</b></span></li>
              <li>答对题数：<span><b>{{scoreNum}}</b>/{{topic.length}}</span></li>
              <li>参与人数：<span>{{result.men}}</span></li>
              <li>您战胜了 <span>{{result.percent}}</span> 的人</li>
            </ul>
          </div>
        </div>
        <div class="desc">
          <span>答题解析</span>
          <div><button @click="showDesc" data-type="1">全部题目</button><button @click="showDesc" data-type="0">错题集</button>
          </div>
        </div>
        <div class="descMain">
          <ul>
            <li v-for="(x, xindex) in topic" v-show="descAll || x.select.type !== x.truth.type">
                <h4>{{xindex+1}}.{{x.question}}</h4>
                <div>您的回答：{{x.select.type}}、{{x.select.text}}<span class="checkIcon" :class="x.select.type !== x.truth.type ? 'error' : ''"></span></div>
                <div><span>正确答案：</span>{{x.truth.type}}、{{x.truth.text}}</div>
                <div v-if="x.desc"><b>答案解析：</b>{{x.desc}}</div>
            </li>
          </ul>
          <div class="txc">
              <button id="restart" @click="restart" class="subBtn">重新答题</button>
          </div>
        </div>
      </div>
    </div>
  </body>
  <script src="js/vue.min.js"></script>
  <script src="js/mui.min.js"></script>
  <script src="js/mui.picker.min.js"></script>
  <script src="js/mock.js"></script>
  <script src="js/jquery.min.js"></script>
  <script src="js/axios.min.js"></script>
  <script>
  axios.defaults.baseURL = 'http://www.sichuanhuayou.cn/hse/index.php/home/index';
  axios.defaults.timeout = 20000;

  var app = new Vue({
    el: '#app',
    data: {
      loaded: false,
      inputName: false,
      started: false,
      myUnit: '',
      myName: '',
      result: {
        ranking: '2',  //成绩排名
        percent: "99%",   // 超过百分之多少人
        men: '80'   //参与人数
      },
      units:[],
      names: [],
      // 题目
      topic: [],
      // 倒计时
      countTime: '30:00',
      // 总共用时
      useTime: 0,
      // 确认交卷
      checked: false,
      // 已交卷
      finished: false,
      // 得分
      score: 0,
      // 答对题数
      scoreNum: 0,
      // 答案解析
      descAll: true
    },
    created () {
      this.getPageData();
    },
    mounted () {
      this.loaded = true;
      var that = this;
      var SET_TIME = null;
      $("#app")[0].onscroll = function () {
        $(".scrollBtn").addClass("show");
        clearTimeout(SET_TIME);
        SET_TIME = setTimeout(function(){
          $(".scrollBtn").removeClass("show");
        }, 1500)
      }
      this.showDesc();
    },
    methods: {
      // 页面数据
      getPageData () {
        //单位及单位成员
        axios.get('/getdw')
        .then((res) => {
          var data = res.data;
          this.units = data
        })
        .catch((res) => {
          mui.alert('加载失败，稍后再试', '提示信息')
        })
        // 所有题目
        axios.get('/GetQuesition')
        .then((res) => {
          var data = res.data;
          this.topic = data
        })
        .catch((res) => {
          mui.alert('加载失败，稍后再试', '提示信息')
        })
      },
      // 筛选错题
      showDesc (e) {
        var that = this;
        if(e){
          that.descAll = e.target.dataset.type == 1 ? true : false;
          $(e.target).addClass("act").siblings().removeClass("act");
        }else{
          $(".desc button").eq(0).addClass("act");
        }
      },
      // 定位错题
      scroll (type) {
        var top = 0;
        type === 0 ? true : top = $("#topic").height();
        $("#app").animate({scrollTop:top},500,"swing");
      },
      // 答题结束
      finish () {
        var that = this;
        if(that.checkAns() === false){
          return false;
        }
        // 做完打分统计错题
        var SINGLE_SCORE = 100/that.topic.length;
        for (var i in that.topic){
          if(that.topic[i].select.type === that.topic[i].truth.type){
            that.score += SINGLE_SCORE;
            that.scoreNum += 1;
          }
        }
        that.score = parseInt(that.score);
        console.warn("答对题数："+that.scoreNum);
        // todo axios;
        that.loaded = false;
        let params = {
          name: that.myName,
          score: that.score,
          dw: that.myUnit
        }
        axios.post('/kao', that.transData(params))
        .then((res) => {
          var data = res.data;
          that.result.percent = data.levels + '%';
          that.result.men = data.joincount;
          that.result.ranking = data.mc;
          that.loaded = true;
          this.finished = true;
        })
        .catch((res) => {
          that.loaded = true;
          mui.alert('加载失败，稍后再试', '提示信息');
        })
      },
      // 答案填充
      fillAnswer (e) {
        var val = e.target.dataset.val.split('|');
        // console.warn(val);
        var tindex = val[0];
        var sIndex = val[1];
        this.topic[tindex].select = this.topic[tindex].answer[sIndex];
        console.log(this.topic[tindex].select.type+":"+this.topic[tindex].select.text)
      },
      // 选择名字
      selectName () {
        var that = this;
        this.picker(this.names,function(res){
          res.value == 0 ? that.inputName = true : that.inputName = false;
          that.inputName === false ? that.myName = res.text : that.myName = '';
          console.log("姓名："+that.myName);
        })
      },
      // 选择单位
      selectUnit () {
        var that = this;
        this.picker(this.units,function(res){
          that.myUnit = res.text;
          that.names = res.names;
          that.myName = res.names[1].text;
          that.inputName = false;
          console.log("所在单位："+that.myUnit)
        })
      },
      picker (data,cab) {
        // data Array
        //普通示例
					var userPicker = new mui.PopPicker();
					userPicker.setData(data);
          userPicker.show(function(items) {
            cab(items[0]);
            //return false;
          });
      },
      restart () {
        window.location.href = window.location.href;
      },
      start (){
        var that = this;
        if(this.myUnit === ''){
          mui.alert('请选择您的单位', '提示信息', function(){
            setTimeout(function(){
              that.selectUnit().show();
            }, 400);
          });
          return false;
        }
        if(this.myName === ''){
          mui.alert('请选择或填写您的名字', '提示信息',function(){
            setTimeout(function(){
              that.selectName().show();
            }, 400);
          });
          return false;
        }
        var COUNT_TIME = 1800;
        var USE_TIME = 0;
        that.started = true;
        that.countTime = that.formatSeconds(COUNT_TIME--)
        var counter = setInterval(function(){
          USE_TIME += 1;
          COUNT_TIME -= 1;
          that.countTime = that.formatSeconds(COUNT_TIME);
          that.useTime = that.formatSeconds(USE_TIME);
          if(that.finished){
            clearInterval(counter);
          }
        }, 1000)
      },
      // 检查未做题
      checkAns () {
        var that = this;
        that.checked = true;
        var list = $("#topic").children("ul");
        // 判断是否做完
        for (var i in that.topic){
          if(that.topic[i].select.type === ''){
            list.children("li").eq(i).addClass("undo");
          }else{
            list.children("li").eq(i).removeClass("undo");
          }
        }
        var top = $($(".undo")[0]).prevAll().length* ($(".undo").height()+30) + 45;
        if($(".undo").length !== 0){
          $("#app").animate({scrollTop:top},500,"swing");
          return false;
        }
        return true;
      },
      // URLSearchParams 
      transData (data) {
        let res = ''
        for (let i in data) {
          res += encodeURIComponent(i) + '=' + encodeURIComponent(data[i]) + '&'
        }
        res = res.substr(0, res.length - 1)
        return res
      },
      formatSeconds (value) {
        var secondTime = parseInt(value);
        var minuteTime = 0;
        var hourTime = 0;
        var result = "";
        if(secondTime > 60) {
            minuteTime = parseInt(secondTime/60);
            secondTime = parseInt(secondTime%60);
            if(minuteTime > 60) {
                hourTime = parseInt(minuteTime/60);
                minuteTime = parseInt(minuteTime%60);
            }
        }
        
        if(hourTime > 0){
          result = turn(hourTime)+":"+turn(minuteTime)+":"+turn(secondTime)
        }else{
          result = turn(minuteTime)+":"+turn(secondTime)
        }
        function turn (num){
          return num >= 0 && num < 10 ? '0'+num : num;
        }
        return result;
      }
    },
  })
  </script>
</html>